package pers.cz.netty.protocal;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: PostGirl-panent
 * @description: 消息解密
 * @author: Cheng Zhi
 * @create: 2022-10-04 15:30
 **/
public class MessageDecoder extends ByteToMessageDecoder {

    private static final Logger log = LoggerFactory.getLogger(MessageDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        // 解密，1、验证魔数
        byte[] bytes = new byte[8];
        ByteBuf byteBuf1 = byteBuf.readBytes(bytes);
        String magicNum = new String(bytes, StandardCharsets.UTF_8);

        if (!ProtocalConst.POCKET_MAGIC_NUM.equals(magicNum)) {
            log.error("未知数据包，magicNum=" + magicNum );
            return;
        }

        // 2、读取消息类型
        byte msgType = byteBuf.readByte();

        final MsgType type = MsgType.getMsgType(msgType);
        if (type == null) {
            log.error("未知操作类型：" + msgType);
            return;
        }

        // 3、读取消息长度
        long contentLenth = byteBuf.readLong();
        Message msg = new Message();
        msg.setMsgType(type);
        msg.setContentLength(contentLenth);
        if(contentLenth > 0){
            // 4、读取内容大小
            byte[] contents = new byte[(int) contentLenth];
            byteBuf.readBytes(contents,0, (int) contentLenth);
            ByteArrayInputStream bis=new ByteArrayInputStream(contents);
            ObjectInputStream ois=new ObjectInputStream(bis);
            msg.setContent(ois.readObject());
        }
        //byte[] bytesSymbol = new byte[10];
        //ByteBuf byteBufSymbol = byteBuf.readBytes(bytesSymbol);
        list.add(msg);
    }
}
